<template>
  <div class="index-page" v-show="isAuth">
    <div class="user-info">
      <div class="line-1">
        <div :style="avatarBackground" class="avatar"></div>
        <div class="text-area">
          <div class="name">{{ userInfo ? userInfo.nickName : '--' }}</div>
          <div
            class="target"
          ><span v-show="showTargetTitle">目标：</span>{{ extraUserInfo && extraUserInfo.targetText ? extraUserInfo.targetText : '--'}}</div>
        </div>
        <config-btn @on-click="showTargetSetting = true"></config-btn>
      </div>
      <div class="line-2">
        <div class="child-line">
          <div class="child-line-title">考试时间</div>
          <div class="time-content">{{ examTime }}</div>
        </div>
        <div class="child-line">
          <div class="child-line-title">目标分数</div>
          <div class="score-area">
            <van-tag plain round type="primary" class="score-tag" color="#C8C9CC">
              <span class="score-tag-text">总分：{{ targetScoreTotal }}</span>
            </van-tag>
            <van-tag plain round type="primary" class="score-tag" color="#C8C9CC">
              <span class="score-tag-text">听力：{{ targetScoreListening }}</span>
            </van-tag>
            <van-tag plain round type="primary" class="score-tag" color="#C8C9CC">
              <span class="score-tag-text">口语：{{ targetScoreSpeaking }}</span>
            </van-tag>
            <van-tag plain round type="primary" class="score-tag" color="#C8C9CC">
              <span class="score-tag-text">阅读：{{ targetScoreReading }}</span>
            </van-tag>
            <van-tag plain round type="primary" class="score-tag" color="#C8C9CC">
              <span class="score-tag-text">写作：{{ targetScoreWriting }}</span>
            </van-tag>
          </div>
        </div>
      </div>
    </div>
    <div class="count-down-area" v-if="extraUserInfo.countDownSwitch">
      <div class="cup-area"></div>
      <div class="exam-time-text">距离考试还有：</div>
      <van-count-down
        v-if="remainTime && remainTime > 0"
        class="custom"
        :time="remainTime"
        :format="countDownFormat"
      />
      <div v-else>--:--:--</div>
    </div>
    <div class="count-down-area" v-else>
      <div class="cup-area"></div>
      <div class="exam-time-text">名言：好好学习，天天向上</div>
    </div>
    <div class="today-daka-area">
      <div class="title-area">
        <div class="big-title">今日打卡记录</div>
        <div class="check-all-record" @click="showAllRecord">查看全部记录</div>
      </div>
      <div class="progress-area">
        <div class="van-progress-area" :key="index" v-for="(item, index) in processArray">
          <van-progress
            :percentage="item.percentage"
            :show-pivot="false"
            stroke-width="8.5px"
            track-color="E3E5E7"
            :color="item.color"
          />
        </div>
      </div>
    </div>
    <div class="card-area">
      <div class="edit-btn" @click="jumpToEditCard">
        <div class="edit-btn-text" >编辑</div>
        <div class="edit-btn-icon"></div>
      </div>
      <van-tabs animated @change="changeTab">
        <van-tab title="全部">
          <card-area @clickCard="clickCard" :data="pocket" card-type="all" />
        </van-tab>
        <van-tab title="听力">
          <card-area @clickCard="clickCard" :data="pocketListening" card-type="listening" />
        </van-tab>
        <van-tab title="口语">
          <card-area @clickCard="clickCard" :data="pocketSpeaking" card-type="speaking" />
        </van-tab>
        <van-tab title="阅读">
          <card-area @clickCard="clickCard" :data="pocketReading" card-type="reading" />
        </van-tab>
        <van-tab title="写作">
          <card-area @clickCard="clickCard" :data="pocketWriting" card-type="writing" />
        </van-tab>
      </van-tabs>
    </div>
    <target-setting
      :userInfo="userInfo"
      :extraUserInfo="extraUserInfo"
      :goal="goal"
      :showTargetSetting="showTargetSetting"
      @commit="commitTargetSetting"
      @dataUpdated="$emit('updateTargetInfo')"
      @showLoading="$emit('showLoading')"
    ></target-setting>
    <swiper-component
      :cardData="cardData"
      v-if="showPopup"
      @commit="commitDaka"
      @cancel="cancelDaka"
      @showLoading="$emit('showLoading')"
      @hideLoading="$emit('hideLoading')"
    ></swiper-component>
    <!-- <ball-in-progress></ball-in-progress> -->
    <complete-view v-if="completeView" @close="closeCompleteView" :dakaData="dakaData"></complete-view>
  </div>
</template>

<script>
const DEFAULT_AVATAR = "";
const colorArray = ["#FFA6B8", "#FFD733", "#DDF5F3"];
import configBtn from "../components/configBtn";
import cardArea from "../components/cardArea";
import swiperComponent from "../components/swiperComponent";
// import ballInProgress from '../components/ballInProgress';
import targetSetting from "../components/targetSetting";
import completeView from "../components/completeView";
import { formatTimeChinese, formatDay } from "../../../utils/index";
import colorMap from "../../../config/colorMap";
import { easeInOut } from "../../../utils/animate";
export default {
  components: {
    configBtn,
    cardArea,
    swiperComponent,
    targetSetting,
    completeView
  },
  data() {
    return {
      remainTime: 0,
      firstLoad: true,
      showPopup: false, // 出现打卡页面
      showTargetSetting: false, // 出现个人设置页面
      processArray: new Array(5).fill(
        Object.assign(
          {},
          {
            dakaRecordId: null,
            color: "#E3E5E7",
            percentage: 0
          }
        )
      ),
      cardData: null,
      completeView: false,
      dakaData: null,
      nowString: formatDay(new Date())
    };
  },
  methods: {
    closeCompleteView() {
      this.completeView = false;
      this.dakaData = null;
      setTimeout(() => {
        this.$emit("updateDakaRecordLists");
      }, 200);
    },
    commitTargetSetting() {
      this.showTargetSetting = false;
      this.$emit("reload");
    },
    changeTab(ev) {
      const title = ev.mp.detail.title;
      const keyMap = {
        全部: "all",
        阅读: "reading",
        听力: "listening",
        口语: "speaking",
        写作: "writing"
      };
      this.$emit("changeTab", keyMap[title]);
    },
    changeProgressArray(flag) {
      // 每次改变，只有最后一个array有动效
      // dakaRecordLists只取后5个
      const sliceProgressArray = this.dakaRecordLists.slice(-5);
      const lastIndex = sliceProgressArray.length - 1;
      if (lastIndex === -1) return;
      sliceProgressArray.forEach((item, index) => {
        if (index !== lastIndex) {
          this.$set(this.processArray, index, {
            dakaRecordId: item._id,
            color: colorMap[item.cardType],
            percentage: 100
          });
        }
      });
      this.$set(this.processArray, lastIndex, {
        dakaRecordId: sliceProgressArray[lastIndex]._id,
        color: colorMap[sliceProgressArray[lastIndex].cardType],
        percentage: flag ? 100 : 0
      });
      if (!flag) this.fillLastProgressAnimate(lastIndex);
    },
    fillLastProgressAnimate(index) {
      let percentage = 0;
      let time = 0; // ms
      const MaxTime = 600;
      const addHandler = () => {
        setTimeout(() => {
          time += 50;
          percentage = easeInOut(time / MaxTime) * 100;
          this.$set(this.processArray, index, {
            dakaRecordId: this.processArray[index].dakaRecordId,
            color: this.processArray[index].color,
            percentage: percentage
          });
          if (time < MaxTime) {
            addHandler();
          }
        }, 50);
      };
      addHandler();
    },
    activeProgressUpdate() {
      if (this.firstLoad) {
        this.changeProgressArray(true);
      } else {
        this.changeProgressArray();
      }
      this.firstLoad = false;
    },
    async commitDaka(dakaData) {
      await this.cancelDaka();
      this.showCompleteView(dakaData);
    },
    showCompleteView(dakaData) {
      this.completeView = true;
      this.dakaData = dakaData;
    },
    cancelDaka() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          this.showPopup = false;
          resolve();
        }, 200);
      });
    },
    clickCard({ cardData }) {
      this.showPopup = !this.showPopup;
      this.cardData = cardData;
    },
    showAllRecord() {
      wx.navigateTo({
        url: `/pages/daka/main`
      });
    },
    jumpToEditCard() {
      wx.navigateTo({
        url: "/pages/cardManager/main"
      });
    },
    targetScoreComputedVal(type) {
      if (!this.goal) return "--";
      if (!this.goal[`targetScore${type}`]) return "--";
      return (this.goal[`targetScore${type}`] - 0).toFixed(1);
    },
    calcRemainTime(examTime) {
      const examTimeStamp = new Date(examTime).getTime();
      const now = Date.now();
      this.remainTime = Math.max(examTimeStamp - now, 0);
    }
  },
  props: {
    isAuth: {
      type: Boolean,
      default: true
    },
    userInfo: {
      type: Object,
      default: {
        city: "--",
        country: "--",
        gender: 1,
        language: "zh_CN",
        nickName: "--",
        province: "--",
        avatarUrl: "",
        examTime: null
      }
    },
    goal: {
      type: Object,
      default: {
        targetScoreTotal: "",
        targetScoreListening: "",
        targetScoreSpeaking: "",
        targetScoreReading: "",
        targetScoreWriting: ""
      }
    },
    extraUserInfo: {
      countDownSwitch: true, // 是否开启桌面倒计时
      targetText: "",
      targetCountry: "",
      examTime: ""
    },
    dakaRecordLists: {
      type: Array,
      default: []
    },
    pocket: {
      type: Array,
      default: []
    },
    pocketType: {
      type: String
    }
  },
  computed: {
    // 我是家长、我是老师 不应该显示“目标”
    showTargetTitle() {
      const excludedList = ['我是家长', '我是老师'];
      return excludedList.indexOf(this.extraUserInfo.targetText) === -1;
    },
    // 超过100天，不显示秒
    countDownFormat() {
      const maxTime = 8640000000; // 以100天为界
      return this.remainTime > maxTime ? 'DD天 HH时mm分' : 'DD天 HH时mm分ss秒'
    },
    pocketReading() {
      return this.pocket.filter(item => item.cardType === "reading");
    },
    pocketListening() {
      return this.pocket.filter(item => item.cardType === "listening");
    },
    pocketWriting() {
      return this.pocket.filter(item => item.cardType === "writing");
    },
    pocketSpeaking() {
      return this.pocket.filter(item => item.cardType === "speaking");
    },
    avatarBackground() {
      if (!this.userInfo) return "";
      return `background:url(${this.userInfo.avatarUrl}) center center`;
    },
    targetText() {
      if (
        this.userInfo &&
        this.userInfo.targetCountry &&
        this.userInfo.targetPlan
      ) {
        return `去${this.userInfo.targetCountry}${this.userInfo.targetPlan}`;
      }
      return "--";
    },
    examTime() {
      if (!this.extraUserInfo || !this.extraUserInfo.examTime) return "--";
      return formatTimeChinese(new Date(this.extraUserInfo.examTime));
    },
    targetScoreTotal() {
      return this.targetScoreComputedVal("Total");
    },
    targetScoreListening() {
      return this.targetScoreComputedVal("Listening");
    },
    targetScoreReading() {
      return this.targetScoreComputedVal("Reading");
    },
    targetScoreSpeaking() {
      return this.targetScoreComputedVal("Speaking");
    },
    targetScoreWriting() {
      return this.targetScoreComputedVal("Writing");
    }
  },
  mounted() {
    if (this.processArray && this.processArray.length) {
      this.activeProgressUpdate();
    }
  },
  watch: {
    extraUserInfo: {
      deep: true,
      immediate: true,
      handler() {
        if (this.extraUserInfo && this.extraUserInfo.examTime) {
          this.calcRemainTime(this.extraUserInfo.examTime);
        }
      }
    },
    dakaRecordLists() {
      this.activeProgressUpdate();
    }
  }
};
</script>

<style scoped lang="less">
.index-page {
  height: 100vh;
  width: 100vw;
  position: relative;
}
.user-info {
  padding: 20px 25px;
  .score-tag {
    flex: none;
    margin-top: -3px;
  }
  .score-tag + .score-tag {
    margin-left: 6px;
  }
  .score-tag-text {
    font-size: 8px;
    color: #3d475c;
  }
  > .line-1 {
    height: 40px;
    display: flex;
    align-items: center;
    > .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      flex: none;
      margin-right: 11px;
      background-size: 100% 100%;
    }
    > .text-area {
      width: 100%;
      > .name {
        font-size: 18px;
        color: #3d475c;
      }
      > .target {
        font-size: 12px;
        color: #8e95a0;
      }
    }
  }
  > .line-2 {
    margin-top: 16px;
    .child-line {
      display: flex;
      align-items: center;
      > .child-line-title {
        color: #8e95a0;
        font-size: 14px;
        margin-right: 10px;
        flex: none;
      }
      > .time-content {
        color: #3d475c;
        font-size: 16px;
      }
      .score-area {
        display: flex;
        align-items: center;
      }
    }
    .child-line + .child-line {
      margin-top: 6px;
    }
  }
}
.count-down-area {
  padding: 15px;
  background-color: #ddf5f3;
  box-shadow: 0px 10px 20px 0px rgba(212, 212, 212, 0.5);
  border-radius: 10px;
  margin: 25px;
  margin-top: 0px;
  display: flex;
  align-items: center;
  .cup-area {
    width: 26px;
    height: 26px;
    background: url("../../../../static/images/index/cup.png") center center;
    background-size: cover;
    margin-right: 11px;
  }
  .exam-time-text {
    color: #8e95a0;
    font-size: 12px;
    margin-right: 11px;
  }
}
.today-daka-area {
  margin: 30px 25px;
  .title-area {
    display: flex;
    justify-content: space-between;
    .big-title {
      color: #3d475c;
      font-size: 18px;
      font-weight: bold;
    }
    .check-all-record {
      color: #3d475c;
      font-size: 12px;
      margin-top: 9px;
      font-weight: bold;
    }
  }
  .progress-area {
    display: flex;
    height: 9px;
    margin-top: 8px;
    .van-progress-area {
      flex: 1 1 auto;
      width: 100%;
      height: 9px;
      position: relative;
    }
    .van-progress-area + .van-progress-area {
      margin-left: 10px;
    }
  }
}
.card-area {
  margin: 29px 23px 25px 25px;
  position: relative;
  .edit-btn {
    position: absolute;
    right: 0;
    margin-top: 12px;
    z-index: 1;
    width: 52px;
    height: 21px;
    background: #3d475c;
    border-radius: 10px;
    font-size: 12px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    .edit-btn-icon {
      width: 15px;
      height: 15px;
      margin-left: 3px;
      background: url("http://cdn.ielts.group/添加@3x.png") center
        center no-repeat;
      background-size: 100%;
    }
  }
}
</style>